package com.moose.operator.web.service.impl.attachment;

import com.moose.operator.common.SnowflakeIdWorker;
import com.moose.operator.constant.CommonConstant;
import com.moose.operator.mapper.AttachmentRecordMapper;
import com.moose.operator.model.domain.AttachmentRecordDO;
import com.moose.operator.model.dto.AttachmentRecordDTO;
import com.moose.operator.model.dto.FileUploadInfoDTO;
import com.moose.operator.model.dto.UserInfoDTO;
import com.moose.operator.web.service.AttachmentRecordService;
import com.moose.operator.web.service.UserInfoService;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * @author taohua
 */
@Service
public class AttachmentRecordServiceImpl implements AttachmentRecordService {

  @Resource
  private UserInfoService userInfoService;

  @Resource
  private SnowflakeIdWorker snowflakeIdWorker;

  @Resource
  private AttachmentRecordMapper attachmentRecordMapper;

  @Override
  public void batchSaveAttachmentRecord(
      List<FileUploadInfoDTO> attachmentUploadDTOList) {
    UserInfoDTO userInfo = userInfoService.getCurrentUserInfo();

    List<AttachmentRecordDO> attachmentRecordDOList = attachmentUploadDTOList.stream()
        // 上传成功的
        .filter(fileUploadDTO -> fileUploadDTO.getSuccess().equals(CommonConstant.SUCCESS))
        // 转换 AttachmentRecordDO
        .map((fileUploadDTO -> {
          AttachmentRecordDO attachmentRecordDO = new AttachmentRecordDO();
          attachmentRecordDO.setAttachId(snowflakeIdWorker.nextId());
          attachmentRecordDO.setUserId(userInfo.getUserId());
          attachmentRecordDO.setFileUrl(fileUploadDTO.getFileUrl());
          attachmentRecordDO.setETag(fileUploadDTO.getTag());
          return attachmentRecordDO;
        }))
        .collect(Collectors.toList());
    // TODO: judge logic save success
    attachmentRecordMapper.batchInsertAttachmentRecord(attachmentRecordDOList);
  }
}
